import axios from 'axios'
//导入自己封装的回调函数

//导入element-plus的loading模块
import { ElLoading } from 'element-plus'
//导入返回类型

const LOADING = true

class ZZYRequest {
  //封装axios
  instance
  interceptors 
  showLoading 
  Loading

  constructor(config) {
    //创建axios实例
    this.instance = axios.create(config)
    //保存基本信息
    this.showLoading = config.showLoading ?? LOADING
    // 把实例里的拦截器赋值給自己定义的属性
    this.interceptors = config.interceptors

    // 在axios实例上面的interceptors.request 函数上传入两个函数
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    //在axios实例上面的interceptors.response 函数上传入两个函数
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )

    //给所有的实例都添加上拦截器
    this.instance.interceptors.request.use(
      (config) => {
        //显示loding
        if (this.showLoading) {
          this.Loading = ElLoading.service({
            text: '正在加载数据中',
            lock: true,
            background: 'rgba(0,0,0,0.5)'
          })
        }

        return config
      },
      (err) => {
        console.log(err)

        this.Loading?.close()

        return err
      }
    )

    this.instance.interceptors.response.use(
      (res) => {
        //关闭loading
        this.Loading?.close()
        //数据处理之后在返回出去
        const data = res.data
        if (data?.returnCode === '-1001') {
          console.log('请求失败~, 错误信息')
        } else {
          return data
        }
      },
      (err) => {
        this.Loading?.close()

        return err
      }
    )
  }

  //
  request(config) {
    
    return new Promise((resolve, reject) => {
      //判断传过来的有没有interceptors 有的话就把config传进去调用拦截器
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors?.requestInterceptor(config)
      }

      //设置每个请求的loading
      if (config.showLoading === false) {
        this.showLoading = config.showLoading
      }

      //请求成功拦截器
      this.instance
        .request(config)
        .then((res) => {
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res)
          }

          this.showLoading = LOADING
          //将结果返回出去
          resolve(res)
        })
        .catch((err) => {
          this.showLoading = LOADING
          reject(err)
          return err
        })
    })
  }
  get(config) {
    return this.request({ ...config, method: 'GET' })
  }

  post(config) {
    return this.request({ ...config, method: 'POST' })
  }

  delete(config) {
    return this.request({ ...config, method: 'DELETE' })
  }

  patch(config) {
    return this.request({ ...config, method: 'PATCH' })
  }
  put(config) {
    return this.request({ ...config, method: 'PUT' })
  }
}

export default ZZYRequest
